package com.wenwei.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.jaeger.library.StatusBarUtil;
import com.orhanobut.logger.Logger;
import com.squareup.picasso.Picasso;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wenwei.bean.CityBean;
import com.wenwei.bean.ConfigBean;
import com.wenwei.bean.HaveSubscriberBean;
import com.wenwei.bean.HisPointBean;
import com.wenwei.bean.LoginBean;
import com.wenwei.bean.ParkBean;
import com.wenwei.bean.PayResult;
import com.wenwei.bean.SubscriberSuccBean;
import com.wenwei.bean.UserCouponBean;
import com.wenwei.bean.UserInfoBean;
import com.wenwei.bean.UserOrderEndBean;
import com.wenwei.bean.UserOrderingBean;
import com.wenwei.bean.WeChatPayConfigBean;
import com.wenwei.net.ApiManager;
import com.wenwei.net.BaseSubscriber;
import com.wenwei.parking.BaseActivity;
import com.wenwei.parking.BaseApplication;
import com.wenwei.parking.Constant;
import com.wenwei.parking.R;
import com.wenwei.utils.MapUtils;
import com.wenwei.utils.RogerDateUtils;
import com.wenwei.utils.RogerSPUtils;
import com.wenwei.utils.ShareUtils;
import com.wenwei.utils.UserStringUtils;
import com.wenwei.view.CustomDelDialog;
import com.wenwei.view.OpenDialog;
import com.wenwei.view.PaySuccessDialog;
import com.wenwei.view.PaySuccessPw;
import com.wenwei.view.SubscriberDialog;
import com.wenwei.view.SubscriberPw;
import com.wenwei.view.TimeCountUtilView;
import com.wenwei.view.TimeTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class HostActivity extends BaseActivity {

    @Bind(R.id.id_content)
    LinearLayout idContent;
    @Bind(R.id.id_menu)
    LinearLayout idMenu;
    @Bind(R.id.id_drawer)
    DrawerLayout idDrawer;
    @Bind(R.id.menu_head_img)
    CircleImageView menuHeadImg;
    @Bind(R.id.menu_user_nick)
    TextView menuUserNick;
    @Bind(R.id.menu_user_phone)
    TextView menuUserPhone;
    @Bind(R.id.map)
    MapView mMapView;


    AMap aMap;
    MyLocationStyle myLocationStyle;
    @Bind(R.id.yu_start_car)
    TextView yuStartCar;
    @Bind(R.id.yu_start_price)
    TextView yuStartPrice;
    @Bind(R.id.yu_start_address)
    TextView yuStartAddress;
    @Bind(R.id.yu_start_ll)
    LinearLayout yuStartLl;
    @Bind(R.id.yu_end_car)
    TextView yuEndCar;
    @Bind(R.id.yu_end_time)
    TimeTextView yuEndTime;
    @Bind(R.id.yu_end_ll)
    LinearLayout yuEndLl;
    @Bind(R.id.pend_address)
    TextView pendAddress;
    @Bind(R.id.pend_time)
    TimeTextView pendTime;
    @Bind(R.id.pending_ll)
    LinearLayout pendingLl;
    @Bind(R.id.pay_price_shi)
    TextView payPriceShi;
    @Bind(R.id.pay_price_total)
    TextView payPriceTotal;
    @Bind(R.id.pay_price_quan)
    TextView payPriceQuan;
    @Bind(R.id.pay_type_yu)
    TextView payTypeYu;
    @Bind(R.id.pay_type_ali)
    TextView payTypeAli;
    @Bind(R.id.pay_type_we)
    TextView payTypeWe;
    @Bind(R.id.pay_start_ll)
    LinearLayout payStartLl;
    @Bind(R.id.pay_end_ll)
    LinearLayout payEndLl;
    @Bind(R.id.menu_admin)
    TextView adminTv;

    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        isFinish = true;
        StatusBarUtil.setTranslucentForImageViewInFragment(HostActivity.this, 0, null);

        initMap();

    }

    private boolean isFinish;
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        getUserInfo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mMapView.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    private SubscriberDialog mExitLoginDialog;
    private PaySuccessDialog successDialog;

    @OnClick({R.id.ding_wei,R.id.home_user, R.id.home_message, R.id.home_title, R.id.menu_head_img, R.id.menu_head_ll,
            R.id.menu_ting_ce, R.id.menu_qian_bao, R.id.menu_xiao_xi, R.id.menu_li_shi, R.id.menu_lian_xi,
            R.id.menu_she_zhi, R.id.menu_guan_yu, R.id.menu_admin,R.id.yu_start_nav, R.id.yu_start_yu, R.id.yu_start_kai, R.id.yu_start_ll,
            R.id.yu_end_nav, R.id.yu_end_cancel, R.id.yu_end_kai, R.id.yu_end_ll,
            R.id.pend_end, R.id.pending_ll, R.id.pay_price_quan, R.id.pay_type_yu,
            R.id.pay_type_ali, R.id.pay_type_we, R.id.pay_type_ok, R.id.pay_start_ll,
            R.id.pay_success_su, R.id.pay_success_ok, R.id.pay_end_ll,R.id.pay_success_share,R.id.xuan_zhe_you_hui_quan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ding_wei:
                LatLng latLng = new LatLng(aMap.getMyLocation().getLatitude(),aMap.getMyLocation().getLongitude());
                Logger.d("当前位置："+aMap.getMyLocation().getLatitude()+","+aMap.getMyLocation().getLongitude());
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                break;
            case R.id.home_user:
                if (!idDrawer.isDrawerOpen(Gravity.LEFT)) {
                    idDrawer.openDrawer(Gravity.LEFT);
                } else {
                    idDrawer.closeDrawer(Gravity.LEFT);
                }
                break;
            case R.id.home_message:
                Bundle couponB = new Bundle();
                couponB.putInt("type",Constant.COUPON_ALL);
                goActivity(mContext, CouponActivity.class,couponB);
                break;
            case R.id.home_title:
                goActivity(mContext,SearchAddressActivity.class,null,88);
                break;
            case R.id.menu_head_img:
                idDrawer.closeDrawer(Gravity.LEFT);
                goActivity(mContext, UserInfoActivity.class,null,Constant.REQUEST_CODE_INFO);
                break;
            case R.id.menu_head_ll:
                break;
            case R.id.menu_ting_ce:
                idDrawer.closeDrawer(Gravity.LEFT);
                goActivity(mContext, ParkingRecordActivity.class);
                break;
            case R.id.menu_qian_bao:
                idDrawer.closeDrawer(Gravity.LEFT);
                goActivity(mContext, WalletActivity.class);
                break;
            case R.id.menu_xiao_xi:
                idDrawer.closeDrawer(Gravity.LEFT);
                goActivity(mContext, MessageActivity.class);
                break;
            case R.id.menu_li_shi:
                idDrawer.closeDrawer(Gravity.LEFT);
                goActivity(mContext, HistoryPoiActivity.class);
                break;
            case R.id.menu_lian_xi:
//                ConfigBean ub = RogerSPUtils.getObject(mContext, Constant.CONFIG, ConfigBean.class);
                idDrawer.closeDrawer(Gravity.LEFT);
                Intent intent1 = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + 10086);
                intent1.setData(data);
                startActivity(intent1);
                break;
            case R.id.menu_she_zhi:
                idDrawer.closeDrawer(Gravity.LEFT);
                goActivity(mContext, SettingActivity.class);
                break;
            case R.id.menu_guan_yu:
                idDrawer.closeDrawer(Gravity.LEFT);
                goActivity(mContext,AboutActivity.class);
                break;
            case R.id.menu_admin:
                idDrawer.closeDrawer(Gravity.LEFT);
                    goActivity(mContext, AdminActivity.class);

                break;
            case R.id.yu_start_nav:
                showDialog(1,1,"环球中心");
                break;
            case R.id.yu_start_yu:
                addSubscribeOrder(mParkCarId);
                break;
            case R.id.yu_start_kai:
//                addOrder(mParkId);
                addOrder(mParkCarId);
                break;
            case R.id.yu_start_ll:
                break;
            case R.id.yu_end_nav:
                showDialog(1,1,"环球中心");
                break;
            case R.id.yu_end_cancel:
                cancelSubById(mYuOrderId);
//                yuEndLl.setVisibility(View.GONE);
                break;
            case R.id.yu_end_kai:
                openSubscribeParkCar();
                break;
            case R.id.yu_end_ll:

                break;
            case R.id.pend_end:
                if(orderingBean != null){
                    endCharge(orderingBean.getId());
                }
                break;
            case R.id.pending_ll:
                break;
            case R.id.pay_price_quan:
                //选择优惠券

                break;
            case R.id.pay_type_yu:
                mPayPayType = 1;
                payTypeSelect(1);
                break;
            case R.id.pay_type_ali:
                mPayPayType = 3;
                payTypeSelect(2);
                break;
            case R.id.pay_type_we:
                mPayPayType = 2;
                payTypeSelect(3);
                break;
            case R.id.pay_type_ok:
                if(mPayPayType == 3){
                    payOrderAli();
                }else if(mPayPayType == 2){
                    payOrder();
                }else if (mPayPayType == 1){
                    payOrderYu();
                }

                break;
            case R.id.pay_start_ll:
                break;
            case R.id.pay_success_su:
                payEndLl.setVisibility(View.GONE);
                Bundle bundle = new Bundle();
                bundle.putInt("orderId",mOrderId);
                goActivity(mContext,PaySuccessSuActivity.class,bundle);
                break;
            case R.id.pay_success_ok:

                payEndLl.setVisibility(View.GONE);

                break;
            case R.id.pay_end_ll:
                payEndLl.setVisibility(View.GONE);
                break;
            case R.id.pay_success_share:
                payEndLl.setVisibility(View.GONE);
                ShareUtils.showProduct(mContext);
                break;
            case R.id.xuan_zhe_you_hui_quan:
                Bundle couponC = new Bundle();
                couponC.putInt("type",Constant.COUPON_USER);
                couponC.putInt("state",1);//表示支付选择优惠券
                goActivity(mContext, CouponActivity.class,couponC,Constant.REQUES_CODE_COUPON);
                break;

        }
    }


    private int mPayType = -1;
    private void payTypeSelect(int type){
        switch (type){
            case Constant.PAY_TYPE_YU:
                mPayType = Constant.PAY_TYPE_YU;
                payTypeYu.setBackgroundResource(R.drawable.button_state_2);
                payTypeYu.setTextColor(Color.parseColor("#ffffff"));
                payTypeAli.setBackgroundResource(R.drawable.button_state_3);
                payTypeAli.setTextColor(Color.parseColor("#45bcc6"));
                payTypeWe.setBackgroundResource(R.drawable.button_state_3);
                payTypeWe.setTextColor(Color.parseColor("#45bcc6"));
                break;
            case Constant.PAY_TYPE_ALI:
                mPayType = Constant.PAY_TYPE_ALI;
                payTypeYu.setBackgroundResource(R.drawable.button_state_3);
                payTypeYu.setTextColor(Color.parseColor("#45bcc6"));
                payTypeAli.setBackgroundResource(R.drawable.button_state_2);
                payTypeAli.setTextColor(Color.parseColor("#ffffff"));
                payTypeWe.setBackgroundResource(R.drawable.button_state_3);
                payTypeWe.setTextColor(Color.parseColor("#45bcc6"));
                break;
            case Constant.PAY_TYPE_WE:
                mPayType = Constant.PAY_TYPE_WE;
                payTypeYu.setBackgroundResource(R.drawable.button_state_3);
                payTypeYu.setTextColor(Color.parseColor("#45bcc6"));
                payTypeAli.setBackgroundResource(R.drawable.button_state_3);
                payTypeAli.setTextColor(Color.parseColor("#45bcc6"));
                payTypeWe.setBackgroundResource(R.drawable.button_state_2);
                payTypeWe.setTextColor(Color.parseColor("#ffffff"));
                break;
        }
    }


    @Override
    protected void initData() {
        super.initData();


        getCityAndPark();

        getUserExistSubByUserId();
    }


    private int mParkCarId;

    //初始化地图
    private int mMapLev = 2;//当前地图显示级别
    private void initMap(){
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        //定位蓝点
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.icon_dingwei_2x)));
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);

        //监听地图状态改变
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                Logger.d("loading...finish" + cameraPosition.zoom + "," + cameraPosition.target);

//                getParkCar4user("104.072109","30.663513");
                aMap.clear();
                if(cameraPosition.zoom>=12 && cameraPosition.zoom<16){
                    //停车场级别
                    mMapLev = 2;
                    canvasParkView();
                }else if (cameraPosition.zoom>=16){
                    //停车位级别
                    mMapLev = 3;
                    getParkCar4user(cameraPosition.target.longitude+"",cameraPosition.target.latitude+"");
                }else if (cameraPosition.zoom<12){
                    //城市级别
                    mMapLev = 1;
                    canvasCityView();
                }

                cancasLocation();

            }
        });

        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if(mMarker!=null){
                    mMarker.hideInfoWindow();
                }
            }
        });

        aMap.getUiSettings().setZoomControlsEnabled(false);
//
//        mUiSettings.setScrollGesturesEnabled(false);//禁止滑动手势
        aMap.getUiSettings().setTiltGesturesEnabled(false);//禁止倾斜手势
//        mUiSettings.setZoomGesturesEnabled(false);//禁止缩放手势
        aMap.getUiSettings().setRotateGesturesEnabled(false);//这个方法设置了地图是否允许通过手势来旋转

        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));

        //自定义infoWindow
        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(final Marker marker) {
                View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null);//display为自定义layout文件
                TextView msg = (TextView) infoWindow.findViewById(R.id.msg);
                TextView mabiTv = (TextView) infoWindow.findViewById(R.id.mabi);
                final ParkBean bean = (ParkBean) marker.getObject();
                if(bean!= null){
                    mParkCarId = bean.getId();
                    Logger.d("波神:"+bean.toString());
                    msg.setText(bean.getParkName()+ " " + bean.getParkCarNum());
                }
                mabiTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //预约订单
                        if(bean!=null){
//                            addSubscribeOrder(bean.getParkId(),marker);

                            marker.hideInfoWindow();
                            yuStartLl.setVisibility(View.VISIBLE);
                            changeInfoFormParkCar(bean);
                        }
                    }
                });
                return infoWindow;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });

        //监听markView点击事件
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if(mMapLev == 1){
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(13));
                }else if (mMapLev == 2){
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                }else if (mMapLev == 3){
                    final ParkBean bean = (ParkBean) marker.getObject();
                    if(bean!=null){
                        //未预约的车位
                        if(bean.getState() == 0){
                            mMarker = marker;
                            marker.showInfoWindow();
                        }

                    }
                }
                return true;
            }
        });

    }

    private int mParkId;//infowindow的parkerid
    private Marker mMarker;

    //绘制当前位置
    private void cancasLocation(){
        LatLng latLng = new LatLng(aMap.getMyLocation().getLatitude(),aMap.getMyLocation().getLongitude());
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.infoWindowEnable(true);

            //未预约状态
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.icon_dingwei_2x)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        aMap.addMarker(markerOption);
    }
    //初始化用户信息
    private void initUserInfo(){
        if(!isFinish){
            return;
        }
        final UserInfoBean ub = RogerSPUtils.getObject(mContext, Constant.SP_USER_USER_RESULT, UserInfoBean.class);
        if (ub != null ){
//            Glide.with(mContext).load(ub.getAvator()).error(R.drawable.icon1).into(menuHeadImg);
            if(ub.getAvator()==null){
                menuHeadImg.setImageResource(R.drawable.icon1);
            }else {
                Picasso.with(mContext).load(ub.getAvator()).error(R.drawable.icon1).into(menuHeadImg);

            }

            menuUserNick.setText(ub.getNickname());
            menuUserPhone.setText(UserStringUtils.getUserPhone(mContext));
        }
        if(UserStringUtils.isAdmin(mContext)){
            adminTv.setVisibility(View.VISIBLE);
        }else {
            adminTv.setVisibility(View.GONE);
        }
    }

    //获取停车位，params 经纬度
    private BaseSubscriber<ArrayList<ParkBean>> parsSb;
    private void getParkCar4user(String lng ,String lat){
        parsSb = new BaseSubscriber<ArrayList<ParkBean>>(mContext) {
            @Override
            public void onSuccess(ArrayList<ParkBean> parkBeen) {
                Logger.d("有数据："+parkBeen.size());
                canvasMarkView(parkBeen);
            }

            @Override
            public void onError(Throwable e) {
                Logger.d("无数据："+e.toString());
            }
        };
        ApiManager.getInstance().getParkCar4user(parsSb,lng,lat);
    }
    private void canvasMarkView(ArrayList<ParkBean> list) {
        if(list != null){
            for(int i = 0 ; i<list.size() ; i++){
                MarkerOptions markerOption = new MarkerOptions();
                LatLng latLng = new LatLng(Double.parseDouble(list.get(i).getLatitude())
                ,Double.parseDouble(list.get(i).getLongitude()));
                markerOption.position(latLng);
                markerOption.draggable(false);//设置Marker可拖动
                markerOption.infoWindowEnable(true);
                if(list.get(i).getState() == 0){
                    //未预约状态
                    markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.drawable.icon_weizhi_2x)));
                }else if (list.get(i).getState() == 1){
                    //已预约状态
                    markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.mipmap.chewei_2x)));
                }else if(list.get(i).getState() == 2){
                    //已占用
                    markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.mipmap.icon_yizhanyong_2x)));
                }
                // 将Marker设置为贴地显示，可以双指下拉地图查看效果
                markerOption.setFlat(true);//设置marker平贴地图效果
                aMap.addMarker(markerOption).setObject(list.get(i));
            }
        }
    }

    //获取停车场数据
    CityBean mCityBean;
    private BaseSubscriber<CityBean> cityBeanBaseSubscriber;
    private void getCityAndPark(){
        cityBeanBaseSubscriber = new BaseSubscriber<CityBean>(mContext) {
            @Override
            public void onSuccess(CityBean cityBean) {
                mCityBean = cityBean;
            }
        };
        ApiManager.getInstance().getCityAndPark(cityBeanBaseSubscriber);
    }
    private void canvasCityView(){
        if(mCityBean != null){
            for (int i = 0 ; i < mCityBean.getData().size() ; i ++ ){
                MarkerOptions markerOption = new MarkerOptions();
                LatLng latLng = new LatLng(Double.parseDouble(mCityBean.getData().get(i).getLatitude())
                        ,Double.parseDouble(mCityBean.getData().get(i).getLongitude()));
                markerOption.position(latLng);
                markerOption.draggable(false);//设置Marker可拖动
                markerOption.infoWindowEnable(true);
                markerOption.icon(BitmapDescriptorFactory.fromBitmap(getMyBitmap(mCityBean.getData().get(i).getName())));
                // 将Marker设置为贴地显示，可以双指下拉地图查看效果
                markerOption.setFlat(true);//设置marker平贴地图效果
                aMap.addMarker(markerOption).setObject(mCityBean.getData().get(i));
            }
        }
    }
    private void canvasParkView(){
        if(mCityBean != null){
            for (int i = 0 ; i < mCityBean.getData().size() ; i ++ ){
                Logger.d("parkSize："+mCityBean.getData().size());
                for (int i2 = 0 ;i2 < mCityBean.getData().get(i).getParkList().size();i2++){
                    CityBean.DataBean.ParkListBean  bbb = mCityBean.getData().get(i).getParkList().get(i2);
                    if(bbb!=null && !bbb.getLatitude().equals("")) {
                        MarkerOptions markerOption = new MarkerOptions();
                        LatLng latLng = new LatLng(Double.parseDouble(bbb.getLatitude())
                                , Double.parseDouble(bbb.getLongitude()));
                        markerOption.position(latLng);
                        markerOption.draggable(false);//设置Marker可拖动
                        markerOption.infoWindowEnable(true);
                        markerOption.icon(BitmapDescriptorFactory.fromBitmap(getMyBitmapP("" + bbb.getTotalParkCar())));
                        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
                        markerOption.setFlat(true);//设置marker平贴地图效果
                        aMap.addMarker(markerOption).setObject(bbb);
                    }
                }
            }
        }
    }
    protected Bitmap getMyBitmap(String s) {
        Bitmap bitmap = BitmapDescriptorFactory.fromResource(
                R.drawable.icon_cheliang_2x).getBitmap();
        bitmap = Bitmap.createBitmap(bitmap, 0 ,0, bitmap.getWidth(),
                bitmap.getHeight());
        Canvas canvas = new Canvas(bitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(32f);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(getResources().getColor(R.color.colorPrimary));
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        canvas.drawText(s, bitmap.getWidth()/2, 125 ,textPaint);// 设置bitmap上面的文字位置
        return bitmap;
    }

    protected Bitmap getMyBitmapP(String s) {
        Bitmap bitmap = BitmapDescriptorFactory.fromResource(
                R.drawable.ico_park_2x).getBitmap();
        bitmap = Bitmap.createBitmap(bitmap, 0 ,0, bitmap.getWidth(),
                bitmap.getHeight());
        Canvas canvas = new Canvas(bitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(32f);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(getResources().getColor(R.color.white_color));
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        canvas.drawText(s, bitmap.getWidth()/2, 125 ,textPaint);// 设置bitmap上面的文字位置
        return bitmap;
    }

    //获取用户信息
    private BaseSubscriber<UserInfoBean> infoSb;
    private void getUserInfo(){
        infoSb = new BaseSubscriber<UserInfoBean>(mContext) {
            @Override
            public void onSuccess(UserInfoBean userInfoBean) {
                Logger.d("重新获取用户信息+"+userInfoBean.getAvator());
                RogerSPUtils.putObject(mContext, Constant.SP_USER_USER_RESULT,userInfoBean);
                initUserInfo();
            }
        };
        ApiManager.getInstance().getUserInfo(infoSb, UserStringUtils.getUserId(mContext));
    }

    //直接开锁生成订单
    private BaseSubscriber<Object> addOrderSubscriber;
    private void addOrder(int parkCarId){
        Logger.d("车位ID；"+parkCarId);
        addOrderSubscriber = new BaseSubscriber<Object>(mContext) {
            @Override
            public void onSuccess(Object o) {
                Logger.d("开锁成功");
                yuStartLl.setVisibility(View.GONE);
                yuEndLl.setVisibility(View.GONE);
                openDialog();
                getOnGoingOrder();
//                pendingLl.setVisibility(View.VISIBLE);
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("parkCarId",parkCarId);
            jb.put("userId",UserStringUtils.getUserId(mContext));
            Logger.d("直接开锁的parkCarId："+parkCarId);
            ApiManager.getInstance().addOrder(addOrderSubscriber,jb.toString());
        }catch (Exception e){}

    }

    private OpenDialog openD;
    //开锁成功dialog
    private void openDialog(){
        openD = new OpenDialog(HostActivity.this);
        openD.requestWindowFeature(Window.FEATURE_NO_TITLE);
        openD.setDelDialogEvent(new OpenDialog.DelDialogEvent() {
            @Override
            public void onCancel() {
                openD.dismiss();
            }
        });
        openD.show();
    }

    //预约开锁
    private BaseSubscriber<UserOrderingBean> openSubscribeParkCarSb;
    private void openSubscribeParkCar(){
        openSubscribeParkCarSb = new BaseSubscriber<UserOrderingBean>(mContext,true,"请稍后") {
            @Override
            public void onSuccess(UserOrderingBean userOrderingBean) {
                showToast("开锁成功");
                openDialog();
                getOnGoingOrder();
            }
        };
        Logger.d("预约开锁的预约idID："+mSbId);
        ApiManager.getInstance().openSubscribeParkCar(openSubscribeParkCarSb,mSbId);
    }
    //预约订单
    private ParkBean mSubscrberSb;//parkBean
    private int mYuOrderId ;//预约成功后生成的id，用于取消预约
    private BaseSubscriber<SubscriberSuccBean> addSubscrberSb;
    private void addSubscribeOrder(int parkCardId){
        addSubscrberSb = new BaseSubscriber<SubscriberSuccBean>(mContext) {
            @Override
            public void onSuccess(SubscriberSuccBean o) {
                mYuOrderId = o.getId();
//                marker.hideInfoWindow();
//                yuStartLl.setVisibility(View.VISIBLE);
                    mSbId = o.getId();
                    mExitLoginDialog = new SubscriberDialog(HostActivity.this);
                    mExitLoginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    mExitLoginDialog.setDelDialogEvent(new SubscriberDialog.DelDialogEvent() {
                        @Override
                        public void onCancel() {
                            mExitLoginDialog.dismiss();
                        }
                    });

                mExitLoginDialog.show();
                yuStartLl.setVisibility(View.GONE);
                yuEndLl.setVisibility(View.VISIBLE);
                getUserExistSubByUserId();
            }

            @Override
            public void onError(Throwable e) {
                Logger.d("params:"+e.toString());
                showToast(e.getMessage());
            }
        };
        try{
            JSONObject jb = new JSONObject();
//            jb.put("createTime","1993-03-15");
            jb.put("parkCarId",mParkCarId );
            jb.put("userId",UserStringUtils.getUserId(mContext));
            ApiManager.getInstance().addSubscribeOrder(addSubscrberSb,jb.toString());
        }catch (Exception e){};
    }
    //取消预约订单
    private BaseSubscriber<Object> cancelSb;
    private void cancelSubById(int orderId){
        cancelSb = new BaseSubscriber<Object>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(Object o) {
                showToast("取消成功");
                yuEndLl.setVisibility(View.GONE);
            }
        };
        ApiManager.getInstance().cancelSubById(cancelSb,orderId);
    }
    //第一步：先查询用户是否已有预约订单
    private int mSbId;//预约id
    private BaseSubscriber<HaveSubscriberBean> haveSubscriberBeanBaseSubscriber;
    private void getUserExistSubByUserId(){
        haveSubscriberBeanBaseSubscriber = new BaseSubscriber<HaveSubscriberBean>(mContext) {
            @Override
            public void onSuccess(HaveSubscriberBean haveSubscriberBean) {
                //展示用户已预约的订单
                Logger.d("有预约订单");
                mSbId = haveSubscriberBean.getId();
                mParkId = haveSubscriberBean.getParkCarId();
                yuEndLl.setVisibility(View.VISIBLE);
                mYuOrderId = haveSubscriberBean.getId();
                changeInfoFormSub(haveSubscriberBean);
            }

            @Override
            public void onError(Throwable e) {
                //如果请求失败，表示未有预约订单，再查询用户是否有进行中的订单
                Logger.d("没有预约订单 == 查询进行中的订单");
                getOnGoingOrder();
            }
        };
        ApiManager.getInstance().getUserExistSubByUserId(haveSubscriberBeanBaseSubscriber,UserStringUtils.getUserId(mContext));
    }
    //第二步：当已有预约订单不执行，反之查询用户进行中的订单
    private int mOrderId;
    private UserOrderingBean orderingBean;
    private int mCouponId = 0;//优惠券id
    private float mTotalPrice = 0;//实际支付金额
    private BaseSubscriber<UserOrderingBean> userOrderingBeanBaseSubscriber;
    private void getOnGoingOrder(){
        userOrderingBeanBaseSubscriber = new BaseSubscriber<UserOrderingBean>(mContext) {
            @Override
            public void onSuccess(UserOrderingBean userOrderingBean) {
                Logger.d("波神："+userOrderingBean.toString());
                Logger.d("查询到有进行中的订单+"+userOrderingBean.getState());
                //根据订单的不同状态，界面上做相应的处理
                orderingBean = userOrderingBean;
                mOrderId = userOrderingBean.getId();
                if(userOrderingBean.getState() == 1){
                    //已结束计费，未支付订单
                    mTotalPrice = userOrderingBean.getOrderAmount();
                    payStartLl.setVisibility(View.VISIBLE);
                    payPriceShi.setText(userOrderingBean.getOrderAmount()+"元");
                    payPriceQuan.setText("优惠券：未使用");
                    payPriceTotal.setText("总费用："+userOrderingBean.getOrderAmount()+"元");
                }else if (userOrderingBean.getState() == 0){
                    //正在使用的订单
                    pendingLl.setVisibility(View.VISIBLE);
                    pendAddress.setText(userOrderingBean.getParkName()+" "+userOrderingBean.getParkNum());
                    long l1 = RogerDateUtils.getCurrentTime();
                    long l2 = userOrderingBean.getCreateTime();
                    long l3 = l1 - l2;
                    pendTime.setTimes(l3,1);
                }
            }

            @Override
            public void onError(Throwable e) {
                //此时表示未有进行中的订单
                Logger.d("没有查询到进行中的订单");
            }
        };
        ApiManager.getInstance().getOnGoingOrder(userOrderingBeanBaseSubscriber,UserStringUtils.getUserId(mContext));
    }
    private void changeInfoFormCoupon(UserCouponBean bean){
        if(bean == null){
            mCouponId = 0;
            payPriceQuan.setText("优惠券：未使用");
            payPriceShi.setText(mTotalPrice+"元");
            return;
        }
        mCouponId = bean.getCouponId();
        payPriceQuan.setText("优惠券："+bean.getCoupon().getDiscount()+"折");
        payPriceShi.setText(mTotalPrice*(bean.getCoupon().getDiscount()/10)+"元");
    }
    private void changeInfoFormSub(HaveSubscriberBean sb){
        yuEndCar.setText(sb.getParkName()+ " " + sb.getParkCarNum());
        long l1 = RogerDateUtils.getCurrentTime();
        long l2 = sb.getCreateTime();
        TimeCountUtilView timeCountUtil = new TimeCountUtilView( (Activity)mContext,sb.getSurplusTime()*1000,1000,yuEndTime);
        timeCountUtil.start();
    }
    private void changeInfoFormParkCar(ParkBean bean){
        mParkId = bean.getParkId();
        yuStartCar.setText(bean.getParkName()+" "+bean.getParkCarNum());
        yuStartPrice.setText(bean.getPrice()+"元/小时");
        yuStartAddress.setText("地址："+bean.getParkAddr());
    }
    //结束计费
    private BaseSubscriber<UserOrderEndBean> userOrderEndBeanBaseSubscriber;
    private void endCharge(int orderId){
        userOrderEndBeanBaseSubscriber = new BaseSubscriber<UserOrderEndBean>(mContext) {
            @Override
            public void onSuccess(UserOrderEndBean userOrderingBean) {
//                mOrderId = orderingBean.getId();
                pendingLl.setVisibility(View.GONE);
//                payStartLl.setVisibility(View.VISIBLE);
//                mTotalPrice = orderingBean.getTotalPay();
//                payStartLl.setVisibility(View.VISIBLE);
//                payPriceShi.setText(orderingBean.getTotalPay()+"元");
//                payPriceQuan.setText("优惠券：未使用");
//                payPriceTotal.setText("总费用："+orderingBean.getTotalPay()+"元");
                Logger.d("8888888888888");
                mPayPayType = 1;
                payTypeSelect(1);getOnGoingOrder();
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("id",orderId);
            ApiManager.getInstance().endCharge(userOrderEndBeanBaseSubscriber,jb.toString());
        }catch (Exception e){}

    }
    //订单支付
    private int mPayPayType = 1;
    private BaseSubscriber<WeChatPayConfigBean> paySb;
    private void payOrder(){
        paySb = new BaseSubscriber<WeChatPayConfigBean>(mContext,true,"请稍后") {
            @Override
            public void onSuccess(WeChatPayConfigBean o) {
                Logger.d("获取签名成功");
                weChatPayStart(o);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Logger.d("mmp:"+e.toString());
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("id",mOrderId);
            jb.put("couponId",mCouponId);
            jb.put("payType",mPayPayType);
            Logger.d("支付参数："+jb.toString());
            ApiManager.getInstance().payOrder(paySb,jb.toString());
        }catch (Exception e){

        }
    }
    private BaseSubscriber<String> paySbAli;
    private void payOrderAli(){
        paySbAli = new BaseSubscriber<String>(mContext,true,"请稍后") {
            @Override
            public void onSuccess(final String o) {
                Logger.d("获取签名成功");
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(HostActivity.this);
                        String result = alipay.pay(o, true);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = result;
                        mPayHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Logger.d("mmp:"+e.toString());
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("id",mOrderId);
            jb.put("couponId",mCouponId);
            jb.put("payType",mPayPayType);
            Logger.d("支付参数："+jb.toString());
            ApiManager.getInstance().payOrderAli(paySbAli,jb.toString());
        }catch (Exception e){

        }
    }
    private BaseSubscriber<Object> paySbYu;
    private void payOrderYu(){
        paySbYu = new BaseSubscriber<Object>(mContext,true,"请稍后") {
            @Override
            public void onSuccess(final Object o) {
                mPayPayType = 1;
                successDialog = new PaySuccessDialog(HostActivity.this);
                successDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                successDialog.setDelDialogEvent(new PaySuccessDialog.DelDialogEvent() {
                    @Override
                    public void onCancel() {
                        successDialog.dismiss();
                        payStartLl.setVisibility(View.GONE);
                        payEndLl.setVisibility(View.VISIBLE);
                    }
                });
                successDialog.show();
                payStartLl.setVisibility(View.GONE);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Logger.d("mmp:"+e.toString());
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("id",mOrderId);
            jb.put("couponId",mCouponId);
            jb.put("payType",mPayPayType);
            Logger.d("支付参数："+jb.toString());
            ApiManager.getInstance().payOrderYu(paySbYu,jb.toString());
        }catch (Exception e){

        }
    }

    private void weChatPayStart(WeChatPayConfigBean weChatPayBean) {
        String app_id = weChatPayBean.getAppid();
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(mContext, app_id);
        iwxapi.registerApp(app_id);
        PayReq payRequest = new PayReq();
        payRequest.appId = app_id;
        payRequest.partnerId = weChatPayBean.getPartnerid();
        payRequest.prepayId = weChatPayBean.getPrepayid();
        payRequest.nonceStr = weChatPayBean.getNoncestr();
        payRequest.timeStamp = weChatPayBean.getTimestamp();
        payRequest.sign = weChatPayBean.getSign();
        payRequest.packageValue = "Sign=WXPay";
        Logger.d("appID:" + app_id + ",partnerId:" + weChatPayBean.getPartnerid() + ",prepayId:" + weChatPayBean.getPrepayid() + ",nonceStr:" + weChatPayBean.getNoncestr()
                + ",timeStamp:" + weChatPayBean.getTimestamp() + ",sign:" + weChatPayBean.getSign() + ".packageValue:Sign=WXPay");
        //发起请求
        iwxapi.sendReq(payRequest);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event)   {
        Logger.d("支付回调："+event);
        if(event.equals("success")){
            mPayPayType = 1;
            successDialog = new PaySuccessDialog(HostActivity.this);
            successDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            successDialog.setDelDialogEvent(new PaySuccessDialog.DelDialogEvent() {
                @Override
                public void onCancel() {
                    successDialog.dismiss();

                    payStartLl.setVisibility(View.GONE);
                    payEndLl.setVisibility(View.VISIBLE);
                }
            });
            successDialog.show();
            payStartLl.setVisibility(View.GONE);
        }else if (event.equals("reset")){
            getUserExistSubByUserId();
        }
    }


    private void showDialog(final double lng , final double lat ,final String address) {
        final ActionSheetDialog dialog = new ActionSheetDialog(mContext, new String[]{"百度地图", "高德地图"}, null);
        dialog.title("选择导航方式");
        dialog.show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                Logger.d("当前位置：" + position);
                if(position == 0){
                    MapUtils.goLocation(mContext,"baiDu",lng,lat,address);
                }else if (position == 1){
                    MapUtils.goLocation(mContext,"gaoDe",lng,lat,address);
                }
                dialog.dismiss();
            }
        });
    }

    private Handler mPayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PayResult payResults = new PayResult((String) msg.obj);
            switch (msg.what) {
                case 1: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        showToast("支付宝支付成功");
                        mPayPayType = 1;
                        successDialog = new PaySuccessDialog(HostActivity.this);
                        successDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        successDialog.setDelDialogEvent(new PaySuccessDialog.DelDialogEvent() {
                            @Override
                            public void onCancel() {
                                successDialog.dismiss();
                                payStartLl.setVisibility(View.GONE);
                                payEndLl.setVisibility(View.VISIBLE);
                            }
                        });
                        successDialog.show();
                        payStartLl.setVisibility(View.GONE);
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        }
                        showToast("支付宝支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };


    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                case Constant.REQUEST_CODE_INFO:
                    getUserInfo();
                    break;
                case 88:
                    double d1 = data.getDoubleExtra("lng",0);
                    double d2 = data.getDoubleExtra("lat",0);
                    LatLng marker1 = new LatLng(d2,
                            d1);
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
                    break;
                case Constant.REQUES_CODE_COUPON:
                    UserCouponBean bean = (UserCouponBean) data.getSerializableExtra("bean");
                    changeInfoFormCoupon(bean);
                    break;
            }
        }
    }
}
